package com.gopay.bis.service.bank.impl.expay;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.TransUtil;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.expay.CmbcAdPayManager;
import com.gopay.bis.service.bank.BankAuthOrderService;
import com.gopay.bis.service.bank.sms.SmsSupportController;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.CmbcConstants;
import com.gopay.common.constants.bank.QueryNeedCertConstants;
import com.gopay.common.constants.bank.SmsConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.ExPayBaseMessage;
import com.gopay.common.domain.bank.cmbc.expay.CmbcExPayMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/**
 * 民生代扣接口
 *
 * @CmbcAdPayServiceImpl.java
 * @author zhengxue
 * @2015-11-9 上午10:58:45 www.gopay.com.cn Inc.All rights reserved.
 */
public class CmbcAdPayServiceImpl implements ExPayInteractRemoteService {
    @Resource(name = "cmbcAdPayManager")
    private CmbcAdPayManager cmbcAdPayManager;
    // 短信验证码处理类
    public SmsSupportController smsController;

    @Resource(name = "bankAuthOrderService")
    private BankAuthOrderService bankAuthOrderService;

    /**
     * 身份认证
     */
    public Result certification(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        CmbcExPayMessage message = new CmbcExPayMessage();
        BeanUtils.copyProperties(baseMsg, message);
        try {
            message = (CmbcExPayMessage) cmbcAdPayManager.certification(message);
            if (message.isFlag() && CmbcConstants.RESP_TYPE_SUCCESS.equals(message.getRetType())
                    && CmbcConstants.VALIDATE_STATUS_SUCCESS.equals(message.getValidStatus())) {
                // 代扣接口认证成功
                result.setModel("flag", true);
                result.setModel("retMsg", message.getRetMsg());
            } else {
                result.setModel("flag", false);
                result.setModel("retMsg", message.getRetMsg());
            }
            result.setSuccess(true);
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6076);
        }
        return result;
    }

    /**
     * 发送短信验证码请求
     */
    public Result sendSms(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        try {
            Map<String, String> smsRes = smsController.sendSMS(baseMsg);
            if (ProcCodeConstants.PROC_CODE_100E6102.equals(smsRes.get("resCode"))) {
                // 短信发送成功
                result.setModel("flag", true);
            } else {
                // 短信发送失败
                result.setModel("flag", false);
            }
            result.setModel("sendCount", smsRes.get("sendCount"));
            result.setModel("retMsg", smsRes.get("retMsg"));
            result.setModel("resCode", smsRes.get("resCode"));
            result.setResultCode(smsRes.get("resCode"));
            result.setSuccess(true);
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6077);
        }
        return result;
    }

    /**
     * 验证短信请求
     */
    public Result checkSms(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        try {
            Map<String, String> smsRes = smsController.checkSMS(baseMsg);
            if (ProcCodeConstants.PROC_CODE_100E6091.equals(smsRes.get("resCode"))) {
                // 验证通过
                result.setModel("flag", true);
            } else {
                // 验证失败
                result.setModel("flag", false);
                if (!ProcCodeConstants.PROC_CODE_100E6099.equals(smsRes.get("resCode"))) {
                    Map<String, String> freezeRes = smsController.freezeCard(baseMsg);
                    if (freezeRes != null)
                        smsRes = freezeRes;
                }
            }
            result.setModel("failCount", smsRes.get("failCount"));
            result.setModel("retMsg", smsRes.get("retMsg"));
            result.setModel("resCode", smsRes.get("resCode"));
            result.setResultCode(smsRes.get("resCode"));
            result.setSuccess(true);
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6078);
        }
        return result;
    }

    /**
     * 代扣请求
     */
    public Result payment(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        baseMsg.setBankOrderId("CM" + TransUtil.processOrderIdTo14Digit(baseMsg.getOrderId()));
        CmbcExPayMessage message = new CmbcExPayMessage();
        BeanUtils.copyProperties(baseMsg, message);
        try {
            message = (CmbcExPayMessage) cmbcAdPayManager.payment(message);
            result.setModel("res", message);
            result.setDefaultModel(message.isFlag());
            Map<String, String> param = new HashMap<String, String>();

            if (message.isFlag() && CmbcConstants.RESP_TYPE_SUCCESS.equals(message.getRetType())
                    && CmbcConstants.EXEC_CODE_SUCCESS.equals(message.getRetCode())) {
                // 验签成功
                param.put("orderId", message.getOrderId());
                param.put("amt", baseMsg.getAmount().toString());
                param.put("cardType", "Unknown");
                param.put("notifyNum", "1");
                param.put("payStatus", "00");
                param.put("retCode", "00");
                param.put("retMsg", "验签成功");
                param.put("isFront", String.valueOf(false));
                result.setModel("isNotifyCashier", param);
                result.setSuccess(true);
                result.setOrderStatus(true);
            } else {
                // 通知后台地址该订单失败
                param.put("orderId", baseMsg.getOrderId());
                param.put("amt", baseMsg.getAmount().toString());
                param.put("cardType", "Unknown");
                param.put("notifyNum", "1");
                param.put("payStatus", "01");
                param.put("retCode", "01");
                param.put("retMsg", message.getRetMsg());
                param.put("isFront", String.valueOf(false));
                result.setModel("isNotifyCashier", param);
                result.setSuccess(true);
                result.setOrderStatus(false);
                result.setBankRetCode(message.getBankRetCode());//add by liuyu, 20170803, 快捷支付API失败通知
            }
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6057);
        }
        return result;
    }

    /**
     * 订单查询
     */
    public Result queryOrder(ExPayBaseMessage base) {
        Result result = new Result(false);
        CmbcExPayMessage message = new CmbcExPayMessage();
        BeanUtils.copyProperties(base, message);
        try {
            message = (CmbcExPayMessage) cmbcAdPayManager.query(message);
            result.setDefaultModel(message);
            result.setSuccess(true);
            if (BisPayCheckUtils.checkExternalOrderID(base.getOrderId())) {
                Map<String, String> param = new HashMap<String, String>();
                String amount = base.getAmount().toString();
                param.put("orderId", base.getOrderId());
                param.put("amount", amount);
                if (message == null) {
                    // 查询结果为空
                    param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
                    param.put("returnMessage", "银行返回对账结果为空");
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    result.setModel("queryResult", param);
                    return result;
                }
                if (message.isFlag()) {
                    if (CmbcConstants.RESP_TYPE_SUCCESS.equals(message.getRetType())
                            && CmbcConstants.EXEC_CODE_SUCCESS.equals(message.getRetCode())
                            && CmbcConstants.RESP_TYPE_SUCCESS.equals(message.getOriRetType())
                            && CmbcConstants.EXEC_CODE_SUCCESS.equals(message.getOriRetCode())) {
                        // 成功处理
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
                        param.put("returnMessage", "交易成功");
                    } else if (CmbcConstants.RESP_TYPE_SUCCESS.equals(message.getRetType())
                            && CmbcConstants.EXEC_CODE_SUCCESS.equals(message.getRetCode())
                            && CmbcConstants.RESP_TYPE_ERROR.equals(message.getOriRetType())
                            && CmbcConstants.EXEC_CODE_NOTEXIST.equals(message.getOriRetCode())) {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                        param.put("returnMessage", "交易流水不存在");
                        result.setBankRetCode(message.getBankRetCode());//add by liuyu, 20170803, 快捷API失败通知
                    } else {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                        param.put("returnMessage", "银行订单正在处理中");
                        result.setBankRetCode(message.getBankRetCode());//add by liuyu, 20170803, 快捷API失败通知
                    }
                } else {
                    param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    param.put("returnMessage", "银行验签失败");
                    result.setBankRetCode(message.getBankRetCode());//add by liuyu, 20170803, 快捷API失败通知
                }
                result.setModel("queryResult", param);
            }
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6058);
        }
        return result;
    }
    
    /**
     * 查询是否需要调用鉴权接口
     */
    public Result queryNeedCert(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        try{
           boolean cerFlag = bankAuthOrderService.checkCardCer(baseMsg);
           if(cerFlag){
               result.setModel("NeedMark", QueryNeedCertConstants.QUERY_RESULT_NONEED);
           }else{
               result.setModel("NeedMark", QueryNeedCertConstants.QUERY_RESULT_NEED);
           }
           result.setSuccess(true);
        }catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6057);
        }
        return result;
    }

    @Override
    public Result sign(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result verify(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result treatyQuery(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result cancel(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refund(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result queryCvn(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }

    public SmsSupportController getSmsController() {
        return smsController;
    }

    public void setSmsController(SmsSupportController smsController) {
        this.smsController = smsController;
    }

    @Override
    public Result refundBack(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }

/*	@Override
	public Result refundQuery(ExPayBaseMessage baseMsg) {
		// TODO Auto-generated method stub
		return null;
	}*/
         
    

        
   
}
